package com.putao.interceptor;

import com.alibaba.fastjson.JSON;
import com.putao.base.JwtUser;
import com.putao.utils.RequestUtils;
import com.putao.utils.StringUtils;
import com.putao.utils.ThreadLocalUtil;
import org.slf4j.Logger;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */
public interface CommonInterceptor {

    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Logger log) throws Exception {
        try {
            StringBuffer requestURL = request.getRequestURL();
            log.error("requestURL = " + requestURL);
            // 将当前用户信息放入到当前线程
            String token = RequestUtils.getToken(request);
            if (StringUtils.isBlank(token)) return true;
            token = token.replace("bearer ", "");
            Jwt jwt = JwtHelper.decode(token);
            String claims = jwt.getClaims();
            String encoded = jwt.getEncoded();
//            System.out.println("claims 原始信息："+claims);       //获取原始信息json字符串
            JwtUser jwtUser = JSON.parseObject(claims, JwtUser.class);
//            System.out.println("access token编码信息："+encoded); //获取编码后的字符串
            log.error("当前线程获取用户信息 = " + jwtUser);
            ThreadLocalUtil.set(jwtUser);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("当前线程获取用户信息失败: " + e.getMessage());
        }
        return true;
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 1、从请求头中获取uuid
        // 2、根据uuid组成key到redis中重置value的时间
        //log.error("----------  删除前用户是： " + ThreadLocalUtil.get());
        ThreadLocalUtil.remove();
        //log.error("----------     删除完成     ----------");
    }

}
